package utils

import (
	"io/ioutil"
	"path/filepath"
	"sort"
	"strings"

	"gitee.com/xuender/toolkit/pb"
	"github.com/mitchellh/go-homedir"
)

// Folder 目录.
func Folder(paths []string) *pb.Folder {
	path := filepath.Join(paths...)
	if path == "" {
		home, err := homedir.Dir()
		if err != nil {
			return &pb.Folder{Error: err.Error()}
		}

		path = home
	}

	ret := &pb.Folder{Path: path}

	fs, err := ioutil.ReadDir(path)
	if err != nil {
		ret.Error = err.Error()

		return ret
	}

	fileInfo := []*pb.FileInfo{}

	for _, f := range fs {
		if f.Name()[0] != '.' {
			fileInfo = append(fileInfo, &pb.FileInfo{
				Name:    f.Name(),
				IsDir:   f.IsDir(),
				Size:    f.Size(),
				ModTime: f.ModTime().Unix(),
			})
		}
	}

	sort.Slice(fileInfo, func(i, j int) bool {
		if fileInfo[i].IsDir == fileInfo[j].IsDir {
			return strings.Compare(fileInfo[i].Name, fileInfo[j].Name) < 0
		}

		return fileInfo[i].IsDir
	})

	ret.Files = fileInfo

	return ret
}
